package com.kye.express.business.order.add_order;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.TimePickerView;
import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxCompoundButton;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.datetimepicker.DateTimePicker;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.order.AddOrderSuccessActivity;
import com.kye.express.business.order.ProtocolActivity;
import com.kye.express.business.order.order_address.AddressListActivity;
import com.kye.express.business.order.remark.RemarkActivity;
import com.kye.express.business.web.KyeWebActivity;
import com.kye.express.databinding.ActivityAddOrderBinding;
import com.kye.express.utils.PhoneUtils;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.BuildConfig;
import com.kye.model.UserSession;
import com.kye.model.bean.order.OrderAddOrderBean;
import com.kye.model.bean.order.OrderAddresses;
import com.kye.model.bean.order.OrderContrabandBean;
import com.kye.model.bean.user.User;

import java.util.Calendar;
import java.util.Date;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function7;
import io.reactivex.functions.Predicate;

public class AddOrderActivity extends BaseAppCompatActivity implements AddOrderContract.AddOrderView {

    private ActivityAddOrderBinding mBinding;
    private AddOrderContract.AddOrderPresenter mPresenter;
    private Dialog mKyeProgressDialog;
    private MaterialDialog mSizeDialog;
    private TimePickerView mTimePickerView;
    /**
     * 是否同意了协议
     */
    private boolean mAgreeProtocol;
    private MaterialDialog mProtocolDialog;
    private MaterialDialog mCheckedContraband2Dialog;
    private MaterialDialog mCheckedContraband3Dialog;

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, AddOrderActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_order);

        initView();
        initEvent();
        initData();
    }

    private void initView() {

    }

    private void initEvent() {
        ToolbarManager.setToolbar(this, mBinding.toolbar);

        RxToolbar.itemClicks(mBinding.toolbar)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<MenuItem>() {
                    @Override
                    public void accept(MenuItem menuItem) throws Exception {
                        // 下单帮助
                        KyeWebActivity.startActivity(AddOrderActivity.this, BuildConfig.HOST_RES + "h5/help/119.html", " 电子面单协议", true);
                    }
                });

        RxView.clicks(mBinding.relativeLayoutAddresses)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        AddressListActivity.startActivityForResult(AddOrderActivity.this, mBinding.getAddress().getGuid());
                    }
                });

        final Observable<CharSequence> editTextCommodities = RxTextView.textChanges(mBinding.editTextCommodities).cache();

        Observable.combineLatest(editTextCommodities, RxView.focusChanges(mBinding.editTextCommodities), new BiFunction<CharSequence, Boolean, Pair<String, Boolean>>() {
            @Override
            public Pair<String, Boolean> apply(CharSequence charSequence, Boolean aBoolean) throws Exception {
                final String string = charSequence.toString().trim();
                return Pair.create(string, !TextUtils.isEmpty(string) && !aBoolean);
            }
        })
                .filter(new Predicate<Pair<String, Boolean>>() {
                    @Override
                    public boolean test(Pair<String, Boolean> stringBooleanPair) throws Exception {
                        return stringBooleanPair.second;
                    }
                })
                .map(new Function<Pair<String, Boolean>, String>() {
                    @Override
                    public String apply(Pair<String, Boolean> stringBooleanPair) throws Exception {
                        return stringBooleanPair.first;
                    }
                })
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        mPresenter.checkContraband(s);
                    }
                });


        RxView.clicks(mBinding.frameLayoutForbid)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        // 违禁品
                        KyeWebActivity.startActivity(AddOrderActivity.this, BuildConfig.HOST_RES + "h5/help/wjp/index.html", " 电子面单协议", true);
                    }
                });

        RxView.clicks(mBinding.linearLayoutSize)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {

                    @Override
                    public void accept(Object o) throws Exception {
                        if (mSizeDialog == null) {
                            mSizeDialog = new MaterialDialog.Builder(AddOrderActivity.this)
                                    .items(R.array.add_order_size_items)
                                    .itemsCallback(new MaterialDialog.ListCallback() {
                                        @Override
                                        public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                            mBinding.setSize(text.toString().trim());
                                        }
                                    })
                                    .build();
                        }

                        mSizeDialog.show();
                    }
                });

        RxView.clicks(mBinding.linearLayoutGoodTime)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mTimePickerView = DateTimePicker.show(AddOrderActivity.this, true, true, true, true, true, false, Calendar.getInstance(), null, new DateTimePicker.DateTimeCallBack() {
                            @Override
                            public void callBack(Date date) {
                                if (date.getTime() < System.currentTimeMillis()) {
                                    ToastManager.show(AddOrderActivity.this, "货好时间不能早于现在");
                                    return;
                                }
                                mBinding.setGoodTime(date);
                            }
                        });
                    }
                });


        Observable.combineLatest(
                editTextCommodities,
                RxTextView.textChanges(mBinding.editTextTotalNumber),
                RxTextView.textChanges(mBinding.editTextWeight),
                RxTextView.textChanges(mBinding.editTextTotalPoll),
                RxTextView.textChanges(mBinding.textViewSize),
                RxTextView.textChanges(mBinding.textViewGoodTime),
                RxCompoundButton.checkedChanges(mBinding.checkBoxProtocol),
                new Function7<CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, Boolean, Boolean>() {
                    @Override
                    public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4, CharSequence charSequence5, CharSequence charSequence6, Boolean aBoolean) throws Exception {
                        return !TextUtils.isEmpty(charSequence) &&
                                !TextUtils.isEmpty(charSequence2) &&
                                !TextUtils.isEmpty(charSequence3) &&
                                !TextUtils.isEmpty(charSequence4) &&
                                !TextUtils.isEmpty(charSequence5) &&
                                !TextUtils.isEmpty(charSequence6) &&
                                aBoolean;
                    }
                }
        )
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.buttonSubmit.setEnabled(aBoolean);
                    }
                });

        RxView.clicks(mBinding.linearLayoutRemark)
                .map(new Function<Object, String>() {
                    @Override
                    public String apply(Object o) throws Exception {
                        return mBinding.textViewRemark.getText().toString().trim();
                    }
                })
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        RemarkActivity.startActivityForResult(AddOrderActivity.this, s);
                    }
                });

        RxView.clicks(mBinding.buttonSubmit)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        final String totalPoll = mBinding.editTextTotalPoll.getText().toString().trim();
                        final String totalNumber = mBinding.editTextTotalNumber.getText().toString().trim();

                        try {
                            if (Integer.parseInt(totalPoll) > Integer.parseInt(totalNumber)) {
                                ToastManager.show(AddOrderActivity.this, "总票数不能大于总件数");
                                return;
                            }
                        } catch (Throwable ignored) {

                        }

                        if (mBinding.getGoodTime().getTime() < System.currentTimeMillis()) {
                            ToastManager.show(AddOrderActivity.this, "货好时间不能早于现在");
                            return;
                        }

                        if (!UserSession.getInstance().getUser().isOrdered()) {
                            if (!mAgreeProtocol) {
                                if (mProtocolDialog == null) {
                                    mProtocolDialog = new MaterialDialog.Builder(AddOrderActivity.this)
                                            .title("用户协议")
                                            .content("为了你的权益，请阅读《用户协议》")
                                            .negativeText(R.string.common_cancel)
                                            .positiveText("立即阅读")
                                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                                @Override
                                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                    ProtocolActivity.startActivityForResult(AddOrderActivity.this);
                                                }
                                            })
                                            .build();
                                }
                                mProtocolDialog.show();

                                return;
                            }
                        }

                        mPresenter.submit(
                                mBinding.getAddress(),
                                mBinding.editTextCommodities.getText().toString().trim(),
                                totalNumber,
                                mBinding.editTextWeight.getText().toString().trim(),
                                totalPoll,
                                mBinding.textViewSize.getText().toString().trim(),
                                mBinding.switchServiceMode.isChecked(),
                                mBinding.getGoodTime(),
                                mBinding.textViewRemark.getText().toString().trim()
                        );
                    }
                });

        RxView.clicks(mBinding.textViewProtocol)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        KyeWebActivity.startActivity(AddOrderActivity.this, BuildConfig.HOST_RES + "h5/help/22.html", " 电子面单协议", true);
                    }
                });
    }

    private void initData() {
        mPresenter = new AddOrderContract.AddOrderPresenter();
        mPresenter.bind(this);
        mPresenter.getAddress();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add_order, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ProtocolActivity.PROTOCOL_ACTIVITY_REQUEST_CODE && resultCode == ProtocolActivity.PROTOCOL_ACTIVITY_RESULT_CODE) {
            mAgreeProtocol = true;
        }

        if (requestCode == RemarkActivity.REMARK_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            mBinding.textViewRemark.setText(data.getStringExtra(RemarkActivity.KEY_REMARK));
        }

        if (requestCode == AddressListActivity.ADDRESS_LIST_ACTIVITY_REQUEST_CODE && resultCode == AddressListActivity.ADDRESS_LIST_ACTIVITY_RESULT_CODE && data != null) {
            mBinding.setAddress((OrderAddresses.Address) data.getSerializableExtra(AddressListActivity.KEY_ADDRESS));
        }
    }

    @Override
    public void onAddress(OrderAddresses.Address addresses) {
        mBinding.setAddress(addresses);
    }

    @Override
    public void onSuccess(OrderAddOrderBean orderAddOrderBean) {
        UserSession.getInstance()
                .getUserForRx()
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        if (user.isLogin()) {
                            AddOrderSuccessActivity.startActivity(AddOrderActivity.this, user.getPhone(), orderAddOrderBean.getOrderCode());
                        }
                        finish();
                    }
                });
    }

    @Override
    public void onCheckedContraband(String msg, OrderContrabandBean bean) {
        if (bean.getIsLegal() == 2) {
            if (mCheckedContraband2Dialog == null) {
                mCheckedContraband2Dialog = new MaterialDialog.Builder(this)
                        .title("温馨提示")
                        .content(msg)
                        .positiveText(R.string.common_confirm)
                        .build();
            }
            if (!mCheckedContraband2Dialog.isShowing()) mCheckedContraband2Dialog.show();
        }

        if (bean.getIsLegal() == 3) {
            if (mCheckedContraband3Dialog == null) {
                mCheckedContraband3Dialog = new MaterialDialog.Builder(this)
                        .title("温馨提示")
                        .content(msg)
                        .positiveText("确认拨打")
                        .negativeText(R.string.common_cancel)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                PhoneUtils.call(AddOrderActivity.this, bean.getMarketingTelphone());
                            }
                        })
                        .build();
            }
            if (!mCheckedContraband3Dialog.isShowing()) mCheckedContraband3Dialog.show();
        }
    }

    @Override
    public void onError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void onLoading() {
        mKyeProgressDialog = KyeProgressDialog.show(this, mKyeProgressDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mKyeProgressDialog);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSizeDialog != null && mSizeDialog.isShowing()) mSizeDialog.dismiss();
        if (mTimePickerView != null && mTimePickerView.isShowing()) mTimePickerView.dismiss();
        if (mProtocolDialog != null && mProtocolDialog.isShowing()) mProtocolDialog.dismiss();
        if (mCheckedContraband2Dialog != null && mCheckedContraband2Dialog.isShowing()) mCheckedContraband2Dialog.dismiss();
        if (mCheckedContraband3Dialog != null && mCheckedContraband3Dialog.isShowing()) mCheckedContraband3Dialog.dismiss();
    }

    public interface CheckListener {
        void onCreateDialog(Dialog dialog);

        void startLoginActivity();

        void checkNameCertification();
    }
}
